package com.hopedove.yieldmanage.activity;

import static org.koin.java.KoinJavaComponent.inject;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.data.Datetime;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.repository.CommonRepository;
import com.hopedove.utils.DateTimeUtil;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.SimpleDialog;
import com.hopedove.yieldmanage.R;
import com.hopedove.yieldmanage.adapter.QueryListAdapter;
import com.hopedove.yieldmanage.domain.net.GetQueryList;
import com.hopedove.yieldmanage.domain.net.SelectDict;
import com.hopedove.yieldmanage.domain.net.UpdateQueryList;
import com.hopedove.yieldmanage.entity.ProductQueryEntity;
import com.hopedove.yieldmanage.entity.SpinnerEntity;
import com.hopedove.yieldmanage.utils.SharedPreUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import kotlin.Lazy;

public class YieldQueryActivity extends BaseActivity implements OnClickListener {
    private Lazy<CommonRepository> commonRepo = inject(CommonRepository.class);
    // 日期布局
    private LinearLayout mDateLl;
    // 日期
    private TextView mDateTv;

    // 工号
    private EditText mJobNumEt;
    // 车号
    private EditText mMachineNoEt;

    /******2017年12月4日 修改，去掉车间选择框*********/
    // 车间 下拉框
    //private Spinner mBmmcSp;
    // 班次 下拉框
    private Spinner mClassesSp;

    // 无标准定额
    private CheckBox mCheckBox;

    // 查询
    private Button mQueryBtn;
    // 保存
    private Button mSaveBtn;

    private TextView mCountTv;

    private ListView mListView;
    // 存储日期
    private String mJobDate = "";

    final private List<String> mBmmcList = new ArrayList<>();
    private ArrayAdapter<String> mBmmcSpAdapter;

    // 保存按钮权限
    private String mSaveQX = "";

    final private List<ProductQueryEntity> mProductList = new ArrayList<>();
    // 保存需要上传服务器的list
    final private List<ProductQueryEntity> mSaveProductList = new ArrayList<>();

    private QueryListAdapter mAdapter;

    // 记录当前选择的项数
    private int mCount;

    /**
     * 无标准定额 勾了 为1 ，不勾选为0
     **/
    private String mStandardQuota = "0";
    private Datetime defaultDatetime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.query_activity);
        getDefaultDate();
        initDate();
        initView();
        initEvent();
        selectDict();
        setSaveBtnStatus();
    }

    private void initDate() {
        mJobDate = defaultDatetime.dateFormatEn();
        // 初始化列表中第一个数据为“请选择”
        mBmmcList.add("请选择");
        // 获取权限
        mSaveQX = (String) SharedPreUtil.getValue(this, SharedPreUtil.CM0140202, "");
        // mSaveQX="0";
    }

    private void initView() {
        mDateLl = findViewById(R.id.query_dateLl);
        mDateTv = findViewById(R.id.query_dateTv);
        mJobNumEt = findViewById(R.id.query_jobNumEt);
        mMachineNoEt = findViewById(R.id.query_machineNoEt);
        mClassesSp = findViewById(R.id.query_classesSp);

        mCheckBox = findViewById(R.id.query_CheckBox);
        mQueryBtn = findViewById(R.id.query_queryBtn);
        mSaveBtn = findViewById(R.id.query_saveBtn);
        mCountTv = findViewById(R.id.query_countTv);
        mListView = findViewById(R.id.query_listView);

        // 设置车间下拉框适配器 数据来源于访问服务器的数据字典
        mBmmcSpAdapter = new ArrayAdapter<>(this, R.layout.yield_spinner_item, mBmmcList);
        mBmmcSpAdapter.setDropDownViewResource(R.layout.yield_spinner_drop_item);

        // 设置班次下拉框适配器 数据来源于arrays.xml文件
        ArrayAdapter<String> classesSpAdapter = new ArrayAdapter<>(this, R.layout.yield_spinner_item, getResources().getStringArray(R.array.classes));
        classesSpAdapter.setDropDownViewResource(R.layout.yield_spinner_drop_item);
        mClassesSp.setAdapter(classesSpAdapter);
        // 设置显示当前日
        mDateTv.setText(defaultDatetime.dateFormatCn());
        // 设置分割线
        mListView.setDivider(getDrawableCompat(R.color.line));
        // 设置分割线高度
        mListView.setDividerHeight(1);
        mAdapter = new QueryListAdapter(this, mProductList);
        mListView.setAdapter(mAdapter);
    }


    /**
     * 初始化事件
     */
    private void initEvent() {
        mDateLl.setOnClickListener(this);
        mQueryBtn.setOnClickListener(this);
        mSaveBtn.setOnClickListener(this);
        mJobNumEt.setOnTouchListener((v, event) -> {
            mAdapter.setFocusIndex(-1);
            return false;
        });
        mMachineNoEt.setOnTouchListener((v, event) -> {
            mAdapter.setFocusIndex(-1);
            return false;
        });
        mAdapter.setOnCheckClickListener((position, isChecked) -> {
            mProductList.get(position).isChecked = isChecked;
            mCount = 0;
            for (int i = 0; i < mProductList.size(); i++) {
                if (mProductList.get(i).isChecked) {
                    mCount++;
                }
            }
            mCountTv.setText("已选择\n" + mCount + "项");
            // 设置保存按钮状态
            setSaveBtnStatus();
        });
        mCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mStandardQuota = "1";
            } else {
                mStandardQuota = "0";
            }
        });
    }

    /**
     * 设置保存按钮的状态
     */
    protected void setSaveBtnStatus() {
        if ("1".equals(mSaveQX) && mCount > 0) {
            mSaveBtn.setEnabled(true);
            mSaveBtn.setBackground(getDrawableCompat(R.drawable.btn_corner_green_dark1));

        } else {
            mSaveBtn.setEnabled(false);
            mSaveBtn.setBackground(getDrawableCompat(R.drawable.btn_corner_gray1));
        }

    }

    /**
     * 获取车间下拉框值
     */
    private void selectDict() {
        showWait();

        SelectDict selectDict = SelectDict.newWorkshop();
        Communication.asyncRequest(selectDict, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    Gson gson = new Gson();
                    List<SpinnerEntity> spinnerEntityList = gson.fromJson(((OkResponse) r).getData(), new TypeToken<List<SpinnerEntity>>() {
                    }.getType());
                    for (SpinnerEntity spinnerEntity : spinnerEntityList) {
                        mBmmcList.add(spinnerEntity.fieldText);
                    }
                    mBmmcSpAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                ToastUtil.longToast(getBaseContext(), ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 准备获取查询产量列表
     * 2017年8月16日修改：车间必须选择
     */
    private void startGetQueryList() {
        String date = mJobDate;
        String machineNo = mMachineNoEt.getText().toString();
        String jobNum = mJobNumEt.getText().toString();
        String bmmc = "";
        String classes;
        if (mClassesSp.getSelectedItemPosition() == 0) {
            classes = "";
        } else {
            classes = mClassesSp.getSelectedItem().toString();
        }

        getQueryList(date, bmmc, machineNo, jobNum, classes, mStandardQuota);
    }

    /**
     * 查询产量列表
     */
    private void getQueryList(String jobDate, String bmmc, String machineNo, String jobNum, String classes, String standardQuota) {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");

        GetQueryList queryList = new GetQueryList(userBean, jobDate, bmmc, machineNo, jobNum, classes, standardQuota);
        Communication.asyncRequest(queryList, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    String page = jsonObj.optString("page");
                    Gson gson = new Gson();
                    List<ProductQueryEntity> list = gson.fromJson(page, new TypeToken<List<ProductQueryEntity>>() {
                    }.getType());
                    mProductList.clear();
                    mProductList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                    checkListView();
                } catch (Exception e) {
                    // ignore
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    /***
     * 准备进行更新保存操作
     */
    private void startUpdateQueryList() {

        // 每次保存之前都要进行清空，可能存在上一次保存失败的情况下，数据还存在list中
        mSaveProductList.clear();
        for (int i = 0; i < mProductList.size(); i++) {
            if (mProductList.get(i).isChecked) {
                // 添加到需要保存的列表中
                mSaveProductList.add(mProductList.get(i));
            }
        }

        if (mProductList.size() == 0) {
            SimpleDialog.show(this, "当前列表为空，请添加数据！");
            stopWait();
            return;
        }

        if (mSaveProductList.size() == 0) {
            SimpleDialog.show(this, "请勾选需要保存的数据！");
            stopWait();
            return;
        }

        for (ProductQueryEntity product : mSaveProductList) {
            if (TextUtils.isEmpty(product.STANDARD_SPEED)) {
                SimpleDialog.show(this, "标准车速不能为空！");

                return;
            }
            if (TextUtils.isEmpty(product.STANDARD_RATE)) {
                SimpleDialog.show(this, "标准转数不能为空");

                return;
            }
            if (TextUtils.isEmpty(product.STANDARD_ONJOB)) {
                SimpleDialog.show(this, "标准开台不能为空！");

                return;
            }
            if (TextUtils.isEmpty(product.STANDARD_QUOTA)) {
                SimpleDialog.show(this, "标准定额不能为空！");

                return;
            }
        }
        updateQueryList(mSaveProductList);
    }

    /**
     * 更新保存数据
     */
    private void updateQueryList(List<ProductQueryEntity> productList) {
        showWait();
        String userBean = (String) SharedPreUtil.getValue(this, SharedPreUtil.USERBEAN, "");

        UpdateQueryList updateQueryList = new UpdateQueryList(userBean, productList);
        Communication.asyncRequest(updateQueryList, r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    SimpleDialog.show(this, "您已成功保存" + mSaveProductList.size() + "条数据！");
                    mSaveProductList.clear();
                    // 保存成功后重新获取列表进行刷新
                    startGetQueryList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.query_dateLl) {
            setDate();
        } else if (id == R.id.query_queryBtn) {
            startGetQueryList();
        } else if (id == R.id.query_saveBtn) {
            startUpdateQueryList();
        }
    }

    /**
     * 检查 listView 是否为空
     */
    private void checkListView() {
        if (mProductList.size() > 0) {
            mListView.setVisibility(View.VISIBLE);
        } else {
            mListView.setVisibility(View.GONE);
        }
    }

    private void getDefaultDate() {
        Datetime datetime = commonRepo.getValue().getServerDateTime(false);
        defaultDatetime = DateTimeUtil.adjustForSpecialShift(datetime);
    }

    /**
     * 设置日期
     */
    private void setDate() {
        // 获取当前年月日
        int year = defaultDatetime.year();
        int month = defaultDatetime.month();
        int day = defaultDatetime.dayOfMonth();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListener, year, month - 1, day);
        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            Datetime datetime = new Datetime(year, month + 1, dayOfMonth);
            mDateTv.setText(datetime.dateFormatCn());
            mJobDate = datetime.dateFormatEn();
        }
    };

}
